package work.huangxin.share.controller.talk;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import work.huangxin.share.constant.RedisConstant;
import work.huangxin.share.domain.other.*;
import work.huangxin.share.globalException.MyException;
import work.huangxin.share.service.impl.*;
import work.huangxin.share.util.CheckAllow;
import work.huangxin.share.util.CheckMessageUtil;
import work.huangxin.share.util.RedisUtil;
import work.huangxin.share.util.ThreadLocalUtil;
import work.huangxin.share.util.status.BaseResponse;
import work.huangxin.share.util.status.CodeEnum;
import work.huangxin.share.util.status.ResponseData;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping("/wx")
public class CommentOperationController {

    @Resource
    private CommentService commentService;
    @Resource
    private ReplayMessageOperationService replayMessageOperationService;
    @Resource
    private UserMessageOperationService userMessageOperationService;
    @Resource
    private NoticeOperationService noticeOperationService;
    @Resource
    private ArticleOperationService articleOperationService;
    @Resource
    private LikeArticleService likeArticleService;
    @Resource
    private WXMessage wxMessage;

    @Autowired
    private CheckAllow check;

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Transactional
    @ApiOperation(value = "保存评论")
    @RequestMapping("/saveComment")
    public BaseResponse saveComment(@RequestBody CommentMessage commentMessage, HttpServletRequest request) {

        Integer userId = check.checkAllow(userMessageOperationService, request);

        if (userId < 0) {
            return ResponseData.out(CodeEnum.SIGNATURE_NOT_ALLOW);
        }
        if (CheckMessageUtil.checkMessage(commentMessage.getCommentContent(), wxMessage)) {
            return ResponseData.error(403, "检测到内容违规,请重新输入");
        }
        //先添加，在查询，然后在保存通知
        commentMessage.setUserId(userId);

        commentService.add(commentMessage);

        CommentMessage commentMessage1 = commentService.findList(commentMessage).get(0);


        ArticleMessage newArticle = articleOperationService.getNewArticleById(commentMessage.getArticleId());

        if (!newArticle.getUserId().equals(userId)) {
            NoticeMessage noticeMessage = new NoticeMessage();
            noticeMessage.setUserId(newArticle.getUserId());
            noticeMessage.setNoticeType(3);
            noticeMessage.setArticleId(commentMessage.getArticleId());
            noticeMessage.setCommentId(commentMessage1.getCommentId());

            noticeOperationService.add(noticeMessage);
        }
        /**
         * 文章评论 + 子评论
         */
        newArticle.setTotalComment(commentService.getTotalComment(commentMessage.getArticleId()) + commentService.getReplyComment(commentMessage.getCommentId()));
        redisUtil.del(RedisConstant.articleById + commentMessage.getArticleId());
        redisUtil.set(RedisConstant.articleById + commentMessage.getArticleId(), newArticle);


        threadPoolExecutor.execute(() -> {
            articleOperationService.update(newArticle);
        });

        return ResponseData.success();
    }


    @Transactional
    @ApiOperation(value = "回复评论")
    @RequestMapping("/saveReplay")
    public BaseResponse saveReplay(@RequestBody ReplayMessage replayMessage, HttpServletRequest request) {

        Integer userId = replayMessage.getUserId();
        UserMessage userMessage = new UserMessage();
        userMessage.setUserId(userId);

        Integer personId = check.checkAllow(userMessageOperationService, request);

        if (personId < 0) {
            return ResponseData.out(CodeEnum.SIGNATURE_NOT_ALLOW);
        }

        if (CheckMessageUtil.checkMessage(replayMessage.getReplayContent(), wxMessage)) {
            return ResponseData.error(403, "检测到内容违规,请重新输入");
        }

        if (userMessageOperationService.findCount(userMessage) == 0) {
            return ResponseData.error(new MyException("数据错误"));
        }

        WXSessionModel user = (WXSessionModel) request.getSession().getAttribute("user");
        WXSessionModel user1 = (WXSessionModel) redisUtil.get("user:" + userId);
        replayMessage.setUserId(user.getUserId());

        replayMessageOperationService.add(replayMessage);


        ReplayMessage replayMessage1 = replayMessageOperationService.findList(replayMessage).get(0);

        System.out.println(replayMessage1);

        NoticeMessage noticeMessage = new NoticeMessage();
        noticeMessage.setReplayId(replayMessage1.getReplayId());
        noticeMessage.setNoticeType(4);

        CommentMessage commentMessage = new CommentMessage();
        commentMessage.setCommentId(replayMessage1.getCommentId());

        CommentMessage commentMessage1 = commentService.findList(commentMessage).get(0);


        Integer articleId = commentMessage1.getArticleId();
        ArticleMessage newArticle = articleOperationService.getNewArticleById(articleId);
        //从数据库中查询
        newArticle.setTotalComment(commentService.getReplyComment(commentMessage1.getCommentId()) + commentService.getTotalComment(articleId));
        redisUtil.del(RedisConstant.articleById + articleId);
        redisUtil.set(RedisConstant.articleById + articleId, newArticle);

        threadPoolExecutor.execute(() -> {
            articleOperationService.update(newArticle);
        });


        noticeMessage.setArticleId(commentMessage1.getArticleId());
        if (replayMessage1.getReplayUserId() == null && !Objects.equals(commentMessage1.getUserId(), personId)) {
            noticeMessage.setUserId(commentMessage1.getUserId());
            noticeOperationService.add(noticeMessage);
        } else if (!Objects.equals(replayMessage1.getReplayUserId(), personId) && replayMessage1.getReplayUserId() != null) {
            noticeMessage.setUserId(replayMessage1.getReplayUserId());
            noticeOperationService.add(noticeMessage);
        }
        return ResponseData.success();
    }

    /**
     *
     * @param commentId
     * @param request
     * @return
     */
    @Transactional
    @ApiOperation(value = "点赞评论+1")
    @PutMapping("/likeComment/{articleId}/{commentId}")
    public BaseResponse getCommentLike(@PathVariable("articleId") Integer articleId,
                                       @PathVariable("commentId") Integer commentId,
                                       HttpServletRequest request) {

        //获得点赞评论的用户id，并且检查用户是否被封禁
        Integer userId = check.checkAllow(userMessageOperationService, request);
        //userId异常
        if (userId <= 0) {
            return ResponseData.out(CodeEnum.BODY_NOT_MATCH,"用户信息异常");
        }
        LikeMessage likeMessage = new LikeMessage();
        likeMessage.setCommentId(commentId);
        likeMessage.setUserId(userId);
        likeMessage.setArticleId(articleId);


        //去数据库中查找这个用户是否给这条评论点过赞
        List<LikeMessage> list = likeArticleService.findList(likeMessage);
        if (list.size() == 0) {
            //没有点过赞，做点赞操作
            likeArticleService.add(likeMessage);
            LikeMessage likeMessage1 = likeArticleService.findList(likeMessage).get(0);
            //从数据库中获取Comment_message
            CommentMessage commentById = commentService.getCommentMessage(commentId);
            //判断该评论是否已经被删除
            if (Objects.isNull(commentById)) {
                return ResponseData.out(CodeEnum.NOT_FOUND, "该评论已经被删除");
            }


            NoticeMessage noticeMessage = new NoticeMessage();
            noticeMessage.setArticleId(articleId);
            noticeMessage.setCommentId(commentId);
            // 2是点赞的类型
            noticeMessage.setNoticeType(2);
            noticeMessage.setUserId(userId);
            //like_id是主键，不需要设置
            noticeMessage.setLikeId(likeMessage1.getLikeId());
            List<NoticeMessage> noticeMessages = noticeOperationService.findList(noticeMessage);
            //自己给自己点赞的话，就不需要提示
            if (noticeMessages.size() == 0 && !commentById.getUserId().equals(userId)) {
                //他人给自己的文章点赞
                noticeOperationService.add(noticeMessage);
            }

            //点赞数+1
            commentById.setTotalCommentLikes(commentById.getTotalCommentLikes() + 1);
            commentService.update(commentById);
        } else {
            //做过点赞操作，再点一次，就是取消点赞，点赞数-1
            CommentMessage commentMessage = commentService.getCommentMessage(commentId);
            if (Objects.isNull(commentMessage)) {
                return ResponseData.out(CodeEnum.NOT_FOUND, "该评论已经被删除");
            }

            NoticeMessage noticeMessage = new NoticeMessage();
            noticeMessage.setArticleId(articleId);
            noticeMessage.setCommentId(commentId);
            // 2是点赞的类型
            noticeMessage.setNoticeType(2);
            noticeMessage.setUserId(userId);
            //like_id是主键，不需要设置
            noticeMessage.setLikeId(list.get(0).getLikeId());
            List<NoticeMessage> noticeMessages = noticeOperationService.findList(noticeMessage);


            likeArticleService.delete(likeMessage);
            noticeOperationService.delete(noticeMessage);
            commentMessage.setTotalCommentLikes(commentMessage.getTotalCommentLikes() > 0 ? commentMessage.getTotalCommentLikes() - 1 : 0);
            commentService.update(commentMessage);
        }
        return ResponseData.success();
    }


}
